<template>
  <el-select
      v-model="change"
      filterable remote clearable
      :placeholder="placeholder"
      :remote-method="remoteMethod"
      :loading="loading">
    <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value"/>
  </el-select>
</template>

<script>
  export default {
    name: 'filterable-select',
    data () {
      return {
        options: [],
        loading: false,
        placeholder: '',
        change: ''
      }
    },
    props: {
      value: {
        default: ''
      },
      name: {
        type: String,
        default: ''
      },
      type: {
        type: String,
        require: true,
        validator: function (value) {
          return ['user', 'sample'].includes(value)
        }
      }
    },
    mounted () {
      let list = {
        'user': '用户',
        'sample': '样品',
      }
      this.placeholder = '请输入' + (this.name ? this.name : list[this.type])
    },
    watch: {
      value () {
        this.change = this.value
      },
      change () {
        this.$emit('input', this.change)
        this.$emit('change')
      }
    },
    methods: {
      remoteMethod (query) {
        this.options = []
        if (query !== '') {
          this.loading = true
          this.$http.get('/filterable/' + this.type, { params: { keyword: query } }).then(res => {
            this.loading = false
            if (res.data.code === 200) {
              this.options = res.data.result
            }
          }).catch(() => {
            this.loading = false
          })
        }
      },
      setOption (options) {
        this.options.push(options)
        this.change = options.value
      }
    }
  }
</script>
<style scoped>

</style>
